package com.alinesno.cloud.base.storage.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.alinesno.cloud.base.storage.entity.StorageFileEntity;

import cn.hutool.core.lang.UUID;

@Component
public class RestfulUploadUtils {

	private static final Logger log = LoggerFactory.getLogger(RestfulUploadUtils.class);

	@Value("${user.home}")
	private String logFileTmp; // 本地文件

	/**
	 * 保存到本地临时目录
	 * 
	 * @param file
	 * @param fileName 
	 * @return
	 */
	public String tmpFile(MultipartFile file, String fileName) {
		try {
			String tempFolder = logFileTmp + File.separator + "uploadTmp";
			File f = new File(tempFolder);
			if (!f.exists()) {
				FileUtils.forceMkdir(new File(tempFolder));
			}
			
			String newFilename= UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
			
			log.debug("上传临时目录:{} , file.getOriginalFilename():{}", tempFolder , file.getOriginalFilename());
			Path path = Paths.get(tempFolder + File.separator + newFilename);
			
			FileUtils.copyInputStreamToFile(file.getInputStream(), path.toFile());

			log.debug("path = {}", path.toFile().getAbsolutePath());
			return path.toFile().getAbsolutePath();
		} catch (IOException e) {
			log.error("图片上传错误:{}", e);
		}

		return null;
	}

	/**
	 * 文件保存
	 * 
	 * @param file
	 * @param finalFilename
	 * @param strategy
	 * @return
	 */
	public StorageFileEntity saveFile(MultipartFile file, String finalFilename, String strategy) {

		return null;
	}

}